<template>
  <div id="app">
    <!-- head -->
    <HeadViewVue :addItem="addItem"> </HeadViewVue>
    <ListViewVue
      v-if="todoList.length!=0"
      :todoList="todoList"
      :finish="finishTodo"
      :deleteTodo="deleteTodo"
    >
    </ListViewVue>
    <FootViewVue
      v-if="todoList.length!=0"
      :todoList="todoList"
      :selectAll="selectAll"
      :deleteFinish="deleteFinish"
    >
    </FootViewVue>
  </div>
</template>

<script>
import FootViewVue from "./components/FootView.vue";
import HeadViewVue from "./components/HeadView.vue";
import ListViewVue from "./components/ListView.vue";
export default {
  name: "App",
  mounted(){
    
    // this.todoList = localStorage.getItem("todoList") ? JSON.parse(localStorage.getItem("todoList")) :[]
    // if(this.todoList.length==0){
    //   this.addDefData()
    //   this.todoList = localStorage.getItem("todoList") ? JSON.parse(localStorage.getItem("todoList")) :[]
    // }

    // const todoList = localStorage.getItem("todoList") ? JSON.parse(localStorage.getItem("todoList")) :[]
    // if(todoList.length==0){
    //   this.addDefData()
    //   this.todoList = localStorage.getItem("todoList") ? JSON.parse(localStorage.getItem("todoList")) :[]
    // }else{
    //   this.todoList = todoList
    // }
  },
  data() {
    return {
      todoList: JSON.parse(localStorage.getItem("todoList")) || []
    };
  },

  watch:{
    todoList:{
      deep:true,
      handler(){
        localStorage.setItem("todoList",JSON.stringify(this.todoList))
      }
    }
  },

  methods: {
    addDefData(){
      const todoList = [
        { id: "001", content: "抽烟", done: false },
        { id: "002", content: "喝酒", done: true },
        { id: "003", content: "嚼槟榔", done: false },
      ]
      localStorage.setItem("todoList",JSON.stringify(todoList))
    },

    //添加一个todo
    addItem(todo) {
      
      this.todoList.unshift(todo);
    },
    //勾选完成or未完成
    finishTodo(id) {
      this.todoList.forEach((todo) => {
        if (todo.id === id) {
          todo.done = !todo.done;
          return;
        }
      });
    },
    //删除一个todo
    deleteTodo(id) {
      this.todoList = this.todoList.filter((todo) => {
        return todo.id != id;
      });
    },
    //全选
    selectAll(isAll) {
      this.todoList.forEach((todo) => {
        todo.done = isAll;
      });
    },
    deleteFinish() {
      this.todoList = this.todoList.filter((todo) => !todo.done);
    },
  },
  components: {
    HeadViewVue,
    ListViewVue,
    FootViewVue,
  },
};
</script>
 
<style scoped lang="less">
#app {
  width: 500px;
  padding: 20px;
  margin: 10px;
  border: 1px solid lightgray;
  border-radius: 5px;
}
</style>

